//
//  CZOauthViewController.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOauthViewController: UIViewController {

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = GlobalBKGColor
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self
            , action: "autofill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.title = "登录"
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        SVProgressHUD.showWithStatus("正在加载")
    }

    @objc private func autofill(){
       let jsString = "document.getElementById('userId').value='305976569@qq.com';document.getElementById('passwd').value='lwp199358'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil )
    }
    
    private lazy var webView: UIWebView = UIWebView()
}

extension CZOauthViewController: UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!
        if !url.absoluteString.hasPrefix(redirect_uri){
            return true
        }else{
            let query = url.query!
            let codeString = "code="
            if query.hasPrefix(codeString){
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                CZPrint(items: "code: \(code)")
                CZUserAccountViewModel.sharedInstance.loadAccessToken(code,callBack: {(error) -> () in
                    if error != nil{
                        SVProgressHUD.showErrorWithStatus("您的网络不给力...")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    }else{
                        self.close()
                        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                        appDelegate.switchRootViewController(CZWelcomeViewController())
                    }
                })
            }else{
                close()
            }
            return false
        }
    }
}